<template>
  <div>
    <div>曲线路径管道TubeGeometry</div>
    <div ref="webgl" id="webgl"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  let scene: any = null;
  let camera: any = null;
  let render: any = null;
  onMounted(() => {
    init();
  });
  function init() {
    scene = new THREE.Scene();
    const width = 500;
    const height = 300;
    camera = new THREE.PerspectiveCamera(30, width / height, 1, 10000);
    camera.position.set(-100, 300, 300);
    camera.lookAt(scene.position);
    render = new THREE.WebGLRenderer();
    render.setSize(width, height);
    webgl.value.appendChild(render.domElement);
    new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);

    // 三维样条曲线
    // const path = new THREE.CatmullRomCurve3([
    //   new THREE.Vector3(-50, 20, 90),
    //   new THREE.Vector3(-10, 40, 40),
    //   new THREE.Vector3(0, 0, 0),
    //   new THREE.Vector3(60, 60, 0),
    //   new THREE.Vector3(70, 0, 80),
    // ]);
    // LineCurve3创建直线段路径
    // const path = new THREE.LineCurve3(new THREE.Vector3(0, 100, 0), new THREE.Vector3(0, 0, 0));

    // p1、p2、p3表示三个点坐标
    // const p1 = new THREE.Vector3(-80, 0, 0);
    // const p2 = new THREE.Vector3(20, 100, 0);
    // const p3 = new THREE.Vector3(80, 0, 100);
    // // 三维二次贝赛尔曲线
    // const path = new THREE.QuadraticBezierCurve3(p1, p2, p3);
    // CurvePath多段路径生成管道案例
    // 创建多段线条的顶点数据
    // 创建多段线条的顶点数据
    const p1 = new THREE.Vector3(0, 0, 100);
    const p2 = new THREE.Vector3(0, 0, 30);
    const p3 = new THREE.Vector3(0, 10, 0);
    const p4 = new THREE.Vector3(30, 0, 0);
    const p5 = new THREE.Vector3(100, 0, 0);
    // 1. 3D直线线段
    const line1 = new THREE.LineCurve3(p1, p2);
    // 2. 三维二次贝塞尔曲线
    const curve = new THREE.QuadraticBezierCurve3(p2, p3, p4);
    // 3. 3D直线线段
    const line2 = new THREE.LineCurve3(p4, p5);

    const CurvePath = new THREE.CurvePath();
    // 三条线拼接为一条曲线
    CurvePath.curves.push(line1, curve, line2);

    // CurvePath:路径   40：沿着轨迹细分数  2：管道半径   25：管道截面圆细分数
    const geometry = new THREE.TubeGeometry(CurvePath as THREE.Curve<THREE.Vector3>, 50, 2, 25);
    const material = new THREE.LineBasicMaterial({
      color: 0xaa1100,
      side: THREE.DoubleSide,
    });
    const mesh = new THREE.Line(geometry, material);
    scene.add(mesh);

    renderFun();
  }
  function renderFun() {
    render.render(scene, camera);
    requestAnimationFrame(renderFun);
  }
</script>
<style lang=""></style>
